# -*- coding: utf-8 -*-

# This code shows an example of text translation from English to Simplified-Chinese.
# This code runs on Python 2.7.x and Python 3.x.
# You may install `requests` to run this code: pip install requests
# Please refer to `https://api.fanyi.baidu.com/doc/21` for complete api document

import requests
import random
from hashlib import md5

# Set your own appid/appkey.
APPID = '20231125001891864'
APPKEY = 'PfwQ8thRKGorLApagb26'

# For list of language codes, please refer to `https://api.fanyi.baidu.com/doc/21`
FROM_LANG = 'en'
TO_LANG =  'zh'

def translate(text):
    endpoint = 'http://api.fanyi.baidu.com'
    path = '/api/trans/vip/translate'
    url = endpoint + path

    query = text

    # Generate salt and sign
    def make_md5(s, encoding='utf-8'):
        return md5(s.encode(encoding)).hexdigest()

    salt = random.randint(32768, 65536)
    sign = make_md5(APPID + query + str(salt) + APPKEY)

    # Build request
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    payload = {'appid': APPID, 'q': query, 'from': FROM_LANG, 'to': TO_LANG, 'salt': salt, 'sign': sign}

    # Send request
    r = requests.post(url, params=payload, headers=headers)
    result = r.json()

    # Show response
    return result['trans_result'][0]['dst']

while True:
    text = input('请输入要翻译的内容：')
    if text == "QUIT":
        break
    print(translate(text))